package com.yangwei.examination.teacher.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.yangwei.examination.student.pojo.AnswerPaper;
import com.yangwei.examination.student.service.AnswerPaperService;
import com.yangwei.examination.teacher.model.TimeLineParam;
import com.yangwei.examination.teacher.pojo.*;
import com.yangwei.examination.teacher.service.*;
import com.yangwei.examination.user.pojo.Student;
import com.yangwei.examination.user.pojo.Teacher;
import com.yangwei.examination.user.service.StudentService;
import com.yangwei.examination.user.service.TeacherService;
import com.yangwei.examination.utils.ResultUtils;
import com.yangwei.examination.utils.ResultVo;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
@Api(tags = "教师编辑测验",description = "教师操作测验")
@RestController
@RequestMapping("/tea/Exam")
public class ExamController {

    @Resource
    private ExamService examService;

    @Resource
    private HandleClassService handleClassService;

    @Resource
    private PaperService paperService;

    @Resource
    private TeacherService teacherService;

    @Resource
    private SchoolService schoolService;

    @Resource
    private StudentService studentService;

    @Resource
    private AnswerPaperService answerPaperService;

    @Resource
    private CorrectAnswerPaperService correctAnswerPaperService;

    //教师 统计功能 List
    @ApiOperation("查当前教师下所有考试是否批改并过滤 显示已批改的")
    @GetMapping("/statistics/list")
    public ResultVo listForStatistics(@RequestParam("id") Long id){
        //根据教师id查询 其被批卷后的exam 对应一个班级
        List<Exam> examList = examService.list(Wrappers.lambdaQuery(Exam.class)
                .eq(Exam::getTeacherId, id)
        );
        //查是否已批卷
        for (Exam exam:examList){

            List<AnswerPaper> answerPaperList = answerPaperService.list(Wrappers.lambdaQuery(AnswerPaper.class)
                    .eq(AnswerPaper::getExamId, exam.getId())
            );
            if (answerPaperList.size()!=0){
                List<CorrectAnswerPaper> correctAnswerPaperList = correctAnswerPaperService.list(Wrappers.lambdaQuery(CorrectAnswerPaper.class)
                        .eq(CorrectAnswerPaper::getAnswerPaperId, answerPaperList.get(0).getId())
                );
                if(correctAnswerPaperList.size()!=0){
                    exam.setCorrectStatus(true);
                    //注入改卷信息 获取批卷时间
                    exam.setCorrectAnswerPaper(correctAnswerPaperList.get(0));
                }

            }

            //HandleClass
            HandleClass handleClass = handleClassService.getById(exam.getHandleClassId());
            QueryWrapper<School> schoolQuery = new QueryWrapper<>();
            schoolQuery.lambda().eq(School::getSchoolId,handleClass.getSchoolId());
            //School
            handleClass.setSchool(schoolService.getOne(schoolQuery));


            QueryWrapper<Student> studentQuery = new QueryWrapper<>();
            studentQuery.lambda()
                    .eq(Student::getClassNum,handleClass.getClassNum())
                    .eq(Student::getMajorName,handleClass.getMajorName())
                    .eq(Student::getSchoolId,handleClass.getSchoolId())
                    .eq(Student::getYear,handleClass.getYear());
            List<Student> studentList = studentService.list(studentQuery);

            //注入试卷信息
            exam.setPaper(paperService.getById(exam.getPaperId()));
            //注入考生列表List<Student>
            handleClass.setStudentList(studentList);
            //注入 HandleClass 连同 School
            exam.setHandleClass(handleClass);

        }

        //过滤未批改的测试
        List<Exam> filteredExamList = examList.stream()
                .filter(Exam::getCorrectStatus)
                .collect(Collectors.toList());

        return ResultUtils.success("查询成功",filteredExamList);
    }


    //发起测试
    @ApiOperation("发起测试")
    @PostMapping("/save")
    public ResultVo save(@RequestBody Exam exam) {
        boolean save = examService.save(exam);
        if (save) {
            return ResultUtils.success("发起成功", null);
        }
        return ResultUtils.error("保存失败", null);
    }


    //多个老师 对应不同的测试列表
    @ApiOperation("多个老师 对应不同的测试列表")
    @GetMapping("/list")
    public ResultVo list(@RequestParam Long teacherId) {

        //倒着查
        QueryWrapper<Exam> examQuery = new QueryWrapper<>();
        examQuery.lambda().orderByDesc(Exam::getUpdateTime).eq(Exam::getTeacherId,teacherId);
        List<Exam> examList = examService.list(examQuery);

        for (Exam exam : examList) {

            List<AnswerPaper> answerPaperList = answerPaperService.list(Wrappers.lambdaQuery(AnswerPaper.class)
                    .eq(AnswerPaper::getExamId, exam.getId())
            );
            if (answerPaperList.size()!=0){
                List<CorrectAnswerPaper> correctAnswerPaperList = correctAnswerPaperService.list(Wrappers.lambdaQuery(CorrectAnswerPaper.class)
                        .eq(CorrectAnswerPaper::getAnswerPaperId, answerPaperList.get(0).getId())
                );
                if(correctAnswerPaperList.size()!=0){
                    exam.setCorrectStatus(true);
                    //注入改卷信息 获取批卷时间
                    exam.setCorrectAnswerPaper(correctAnswerPaperList.get(0));
                }

            }

            //注入连同 HandleClass 和 School
            //HandleClass
            HandleClass handleClass = handleClassService.getById(exam.getHandleClassId());
            QueryWrapper<School> schoolQuery = new QueryWrapper<>();
            schoolQuery.lambda().eq(School::getSchoolId,handleClass.getSchoolId());
            //School
            handleClass.setSchool(schoolService.getOne(schoolQuery));

            //注入考生列表List<Student>
            QueryWrapper<Student> studentQuery = new QueryWrapper<>();
            studentQuery.lambda()
                    .eq(Student::getClassNum,handleClass.getClassNum())
                    .eq(Student::getMajorName,handleClass.getMajorName())
                    .eq(Student::getSchoolId,handleClass.getSchoolId())
                    .eq(Student::getYear,handleClass.getYear());
            List<Student> studentList = studentService.list(studentQuery);
            //注入考生交卷的时间
            for (Student student:studentList){
                AnswerPaper one = answerPaperService.getOne(Wrappers.lambdaQuery(AnswerPaper.class)
                        .eq(AnswerPaper::getStudentId, student.getId())
                        .eq(AnswerPaper::getExamId, exam.getId())
                );
                if (one != null)
                student.setSubmitTime(one.getSubmitTime());
            }

            handleClass.setStudentList(studentList);
            exam.setHandleClass(handleClass);

            //注入试卷信息
            exam.setPaper(paperService.getById(exam.getPaperId()));

            //注入发起考试的老师
            exam.setTeacher(teacherService.getById(exam.getTeacherId()));

            //注入本次测试交卷的人数
            exam.setSubmitCount(answerPaperService.count(Wrappers.lambdaQuery(AnswerPaper.class)
                                    .eq(AnswerPaper::getExamId,exam.getId())
                                )
            );
        }
        return ResultUtils.success("查询成功", examList);
    }

    //教师主页 获取当前日程表
    @ApiOperation("教师主页 获取指定日期的日程表 默认今天")
    @PostMapping("/timeLine/list")
    public ResultVo listForTimeLine(@RequestBody TimeLineParam timeLineParam){

        List<Exam> examList =new ArrayList<>();
        if (timeLineParam.getTime()==null){
            //查询今天的日程
            examList = examService.list(Wrappers.lambdaQuery(Exam.class)
                    .apply("DATE(start_time) = CURDATE()")
                    .eq(Exam::getTeacherId,timeLineParam.getId())
                    .orderByAsc(Exam::getStartTime)
            );
        }else{
            //查询指定日期的日程
            examList = examService.list(Wrappers.lambdaQuery(Exam.class)
                    .apply("DATE(start_time) = {0}", timeLineParam.getTime())
                    .eq(Exam::getTeacherId,timeLineParam.getId())
                    .orderByAsc(Exam::getStartTime)
            );
        }

        for (Exam exam:examList){
            HandleClass handleClass = handleClassService.getById(exam.getHandleClassId());
            handleClass.setSchool(schoolService.getOne(Wrappers.lambdaQuery(School.class)
                    .eq(School::getSchoolId,handleClass.getSchoolId())
            ));
            exam.setPaper(paperService.getById(exam.getPaperId()));
            exam.setHandleClass(handleClass);
        }
        System.out.println(examList);
        return ResultUtils.success("查询成功",examList);
    }

    //批量删除 前端按钮暂时取消
    @ApiOperation("批量删除接入的班级 不包括考试信息和批改信息!")
    @PostMapping("/deleteByIds")
    public ResultVo delExamByIds(@RequestBody Integer[] ids){
        QueryWrapper<Exam> examQuery = new QueryWrapper<>();
        examQuery.lambda().in(Exam::getId,ids);
        boolean flag = examService.remove(examQuery);
        if (flag){
            return ResultUtils.success("删除成功",null);
        }
        return ResultUtils.error("删除失败",null);
    }

}
